package com.aididi.concurrent;

import java.util.concurrent.Executors;
import java.util.concurrent.ThreadPoolExecutor;

import static java.util.concurrent.Executors.*;

/**
 * @Auther: xuzexiang
 * @Date: 2018-11-5 0005 20:35
 * @Description:
 */
public class ThreadLocalDemo {
    public static void main(String[] args) {
        threadDemo commonInstance = new threadDemo();
        Thread t1 = new Thread(commonInstance,"t1--");
        Thread t2 = new Thread(commonInstance,"t2--");
        Thread t3 = new Thread(commonInstance,"t3--");
        Thread t4 = new Thread(commonInstance,"t4--");


        t1.start();
        t2.start();
        t3.start();
        t4.start();

        // wait for threads to end
        try {
            t1.join();
            t2.join();
            t3.join();
            t4.join();
        }catch( Exception e) {
            System.out.println("Interrupted");
        }
    }
}

class threadDemo extends Thread{
    int counter;
    private static ThreadLocal<Integer> threadLocalCounter = new ThreadLocal<Integer>();
    @Override
    public void run() {
        counter++;
        if(threadLocalCounter.get()!=null){
            System.out.println("第一次："+threadLocalCounter.get());
            threadLocalCounter.set(threadLocalCounter.get().intValue()+1);
            System.out.println("第二次："+threadLocalCounter.get());
        }else{
            threadLocalCounter.set(0);
        }
        System.out.println(Thread.currentThread().getName()+"--Counter: " + counter);
        System.out.println(Thread.currentThread().getName()+"--threadLocalCounter: " + threadLocalCounter.get());
        threadLocalCounter.remove();
    }

}
